package com.weactivity.controller;

import com.weactivity.dto.*;
import com.weactivity.entity.Budget;
import com.weactivity.entity.Expense;
import com.weactivity.service.BudgetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/budget")
public class BudgetController {
    @Autowired(required = false)
    private BudgetService budgetService;


    /**
     * 展示活动预算
     *
     * @param
     * @return
     */
    @GetMapping("/show")
    public Result show_budget(){
        List<Budget> budgetList = budgetService.showAll();
        return Result.ok(budgetList);
    }
    /**
     * 添加预算
     *
     * @param budgetDTO
     * @return
     */
    @PutMapping("/add")
    public Result add(@RequestBody BudgetDTO budgetDTO){
        budgetService.add(budgetDTO);
        return Result.ok();
    }

    /**
     * 修改预算
     *
     * @param changeDTO
     *
     * @return
     */
    @PostMapping("/change")
    public Result change(@RequestBody ChangeDTO changeDTO){
        double oldBudget = budgetService.findBudget(changeDTO.getAid());
        double oldRemain = budgetService.findRemain(changeDTO.getAid());
        double temp = changeDTO.getNewBudget() - oldBudget;
        double newRemain = oldRemain + temp;
        if(newRemain < 0){
            return Result.fail("剩余预算不足");
        }
        else{
            budgetService.updateBudget(changeDTO.getNewBudget(),newRemain,changeDTO.getAid());
            return Result.ok();
        }

    }

    /**
     * 申请报销
     *
     * @param applyExpenseDTO
     * @return
     */
    @PutMapping("/apply")
    public Result apply(@RequestBody ApplyExpenseDTO applyExpenseDTO){
        budgetService.apply(applyExpenseDTO);
        return Result.ok();
    }

    /**
     * 展示申请
     *
     * @param state
     * 按照是否操作显示申请
     * @return
     */
    @GetMapping("/showApply")
    public Result showApply(@RequestParam("state") int state){
        List<Expense> expenseList = budgetService.showApply(state);
        return Result.ok(expenseList);
    }

    /**
     * 处理申请
     *
     * @param approveDTO
     * @return
     */
    @PostMapping("/dispose")
    public Result dispose(@RequestBody ApproveDTO approveDTO){

        int approve = approveDTO.getApprove();
        int uid = approveDTO.getUid();
        int aid = approveDTO.getAid();
        if(0 == approve){
            budgetService.dispose1(approveDTO);
        }
        else {
            double money = budgetService.findMoney(approveDTO);
            double remain = budgetService.findRemain(aid);
            if(money > remain){
                return Result.fail("超出预算");
            }
            else {
                double newRemain = remain - money;
                budgetService.dispose2(uid,aid,approve,newRemain);
            }

        }
        return Result.ok();
    }
}
